<template>
  <div class="nav-stats">
    <span class="stat-item">
      <span class="stat-label">访问量</span>
      <span class="stat-value">{{ stats.totalVisits }}</span>
    </span>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { serverAnalyticsService } from '../services/serverAnalytics'
import { getGlobalVersion } from '../composables/useVersion'

interface Stats {
  totalVisits: number
  todayVisits: number
  weekVisits: number
  monthVisits: number
}

const stats = ref<Stats>({
  totalVisits: 0,
  todayVisits: 0,
  weekVisits: 0,
  monthVisits: 0
})

const fetchStats = async () => {
  try {
    const currentVersion = getGlobalVersion()
    const serverStats = await serverAnalyticsService.getStats(currentVersion)
    if (serverStats && serverStats.stats) {
      stats.value = {
        totalVisits: serverStats.stats.totalVisits || 0,
        todayVisits: serverStats.stats.todayVisits || 0,
        weekVisits: serverStats.stats.weekVisits || 0,
        monthVisits: serverStats.stats.monthVisits || 0
      }
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

onMounted(() => {
  fetchStats()
  // 每30秒更新一次数据
  // 确保只在浏览器环境中执行
  console.log('计时器开始判断是否在浏览器环境中执行')
  if (typeof window !== "undefined") {
    console.log('计时器开始，在浏览器环境中执行，开始获取数据')
    fetchStats()
    // 每30秒更新一次数据
    setInterval(fetchStats, 30000)
  }
})
</script>

<style scoped>
.nav-stats {
  display: flex;
  align-items: center;
  gap: 16px;
  font-size: 12px;
  color: var(--vp-c-text-2);
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.stat-label {
  font-weight: 500;
}

.stat-value {
  font-weight: 600;
  color: var(--vp-c-brand);
}
</style> 